﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;

namespace AnycleLiu.Common.Security
{
    /// <summary>
    /// 非对称加密算法RSA帮助类
    /// </summary>
    public class AsymetricAlgorithmHelper
    {
        private RSACryptoServiceProvider rsaPrivider;

        public AsymetricAlgorithmHelper(){
            rsaPrivider = new RSACryptoServiceProvider();
        }

        /// <summary>
        /// 生成密钥
        /// </summary>
        /// <param name="includePrivateKey">是否生成私钥</param>
        /// <returns></returns>
        public string GetKeyXml(bool includePrivateKey=true)
        {
            return rsaPrivider.ToXmlString(includePrivateKey);
        }

        public byte[] Encrypt(byte[] clearBytes, string publicKeyXml)
        {
            rsaPrivider.FromXmlString(publicKeyXml);
            return rsaPrivider.Encrypt(clearBytes, true);
        }

        public byte[] Decrypt(byte[] plainBytes, string privateKeyXml)
        {
            rsaPrivider.FromXmlString(privateKeyXml);
            return rsaPrivider.Decrypt(plainBytes, true);
        }

        public string Encrypt(string cleartext, string publicKeyXml)
        {
            byte[] plainBytes = Encrypt(Encoding.UTF8.GetBytes(cleartext),publicKeyXml);

            return Convert.ToBase64String(plainBytes);
        }

        public string Dncrypt(string plaintext, string privateKeyXml)
        {
            byte[] clearBytes = Encrypt(Convert.FromBase64String(plaintext), privateKeyXml);

            return Encoding.UTF8.GetString(clearBytes);
        }
    }
}
